import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : retainv
 * @date : 2024/3/20 11:30
 */
public class MyLock implements Lock, Serializable {
    private Sync sync = new Sync();

    private static class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected boolean tryAcquire(int arg) {
            // 独占锁只能上锁一次
            assert arg == 1;
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            // 公平锁
//            if (!hasQueuedThreads() && getExclusiveOwnerThread() == Thread.currentThread()) {
            // 非公平锁
            if (getExclusiveOwnerThread() == Thread.currentThread()) {
                // 可重入锁
//                int state = getState();
//                setState(++state);
//                return true;

                // 不可重入锁
                throw new Error("can't acquire lock multiple times!");
            }
            // 没有上锁成功，直接退出
            return false;
        }

        @Override
        protected boolean tryRelease(int arg) {
            // 如果没有持有锁，则不能释放锁
            if (!isHeldExclusively()) {
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        @Override
        protected boolean isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        public Condition newCondition() {
            return new ConditionObject();
        }

        public int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }
    }

    @Override
    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    public int getHoldCount() {
        return sync.getHoldCount();
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }

    static int count = 0;
    public static void main(String[] args) throws Exception {
        new ReentrantLock();
        MyLock myLock = new MyLock();
        myLock.lock();
        myLock.lock();
        myLock.lock();
        System.out.println(myLock.getHoldCount());
        Runnable runnable = () -> {
            try {
                myLock.lock();
                for (int i = 0; i < 10000; i++) {
                    count++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                myLock.unlock();
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        System.out.println(count);
    }
}
